﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Gene
{
    class Clib
    {
        public static char DE(char c, int key) 
        { 
            return (char)(c ^ key);
        }

        public static void printConsole(byte[] b)
        {
            for (int i = 0; i <= b.Length - 1; ++i)
            {
                Console.Write(b[i]);
                Console.Write("|");
            }
        }

        public static byte[] ReadOnly(String some)
        {
            byte[] b = new byte[some.Length];
            if (some == null) { return null; }
            for (int i = 0; i <= some.Length - 1; ++i)
            {
                b[i] = (byte)some.ElementAt(i);
            }
            return b;
        }

        public static byte[] ReadFile(String path)
        {
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            byte[] b = new byte[fs.Length];

            if (fs.CanRead == false)
            {
                MessageBox.Show("File is not FOUND");
                return null;
            }
            fs.Read(b, 0, (int)fs.Length);
            
            return b;
        }

        public static void CreateFile(String path, byte[] bytes)
        {
            FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
            try 
            {
                fs.SetLength(bytes.Length);
                fs.Write(bytes,0,bytes.Length);
            }
            catch { }
            finally 
            {
                fs.Close();
            }
        }

        public static String Feistel(String s, String k)
        {
            String l0, r0;
            if (s.Length % 2 == 1) 
            {
                s = s + '?';
            }
            l0 = s.Substring(0, (s.Length / 2));
            r0 = s.Substring(s.Length / 2, s.Length/2);
            char[] r1 = new char[l0.Length];
            char[] r2 = new char[r0.Length];

            int i = 0, r = 1;
            
            while(r <= r0.Length)
            {
                r1[r - 1] = r0.ElementAt(r - 1);
                r2[r - 1] = (char)((Clib.DE(r0.ElementAt(r - 1), k.ElementAt(i % k.Length))) ^ (l0.ElementAt(r - 1)));
                r++; i++;
                
            }

            return r1.ToString()+r2.ToString();
        }
    }
}
